package com.yf.ccdugtfood.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import android.widget.TextView;
import android.widget.Toast;

import com.yf.ccdugtfood.R;
import com.yf.ccdugtfood.adapter.OrderAdapter;
import com.yf.ccdugtfood.bean.Food;
import com.yf.ccdugtfood.util.Constant;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderActivity extends AppCompatActivity implements View.OnClickListener{
    private ListView lv_order;
    private LinearLayout ly_AddressInfo, ly_remarkInfo;//地址信息 备注信息
    private OrderAdapter orderAdapter;
    private List<Food> carFoodList = new ArrayList<>();
    private TextView tv_title, tv_back,tv_total_cost, tv_payment,tv_total_costing,
            user_name,phone_number,address,tv_remarkContent;
    private String customer,cust_phone,cust_address,amount,order_time,user_id,remarks;
    public static final int MSG_ORDER_OK = 2;
    private BigDecimal money;

    BigDecimal distributionCost = new BigDecimal(1.0); //配送费用

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_ORDER_OK){
                if (msg.obj !=null){
                    String status = msg.obj.toString();
                    Log.i("cc",status);
                    if ("SUCCESS".equals(status.trim())){
                        Toast.makeText(OrderActivity.this,"下单成功",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(OrderActivity.this,SuccessOrderActivity.class);
                        intent.putExtra("carFoodList", (Serializable) carFoodList);
                        intent.putExtra("customer",user_name.getText().toString().trim());
                        intent.putExtra("cust_phone",phone_number.getText().toString().trim());
                        intent.putExtra("cust_address",address.getText().toString().trim());
                        intent.putExtra("amount",tv_total_costing.getText().toString().trim());
                        startActivity(intent);
                    }else {
                        Toast.makeText(OrderActivity.this,"下单失败",Toast.LENGTH_SHORT).show();
                    }
                 }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        //获取购物车中的数据
        carFoodList= (List<Food>) getIntent().getSerializableExtra("carFoodList");
        //获取购物车中菜的总价格
        money=new BigDecimal(getIntent().getStringExtra("totalMoney"));
        initView();
        setData();
    }

    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("订单");
        tv_back = (TextView) findViewById(R.id.tv_back);
        lv_order= (ListView) findViewById(R.id.lv_order);
        tv_total_cost = (TextView) findViewById(R.id.tv_total_cost); //总计
        tv_total_costing = (TextView) findViewById(R.id.tv_total_costing); //待支付
        user_name = (TextView) findViewById(R.id.user_name);
        phone_number = (TextView) findViewById(R.id.phone_number);
        address = (TextView) findViewById(R.id.address);
        tv_remarkContent = (TextView) findViewById(R.id.tv_remarkContent);
        tv_payment = (TextView) findViewById(R.id.tv_payment);
        ly_remarkInfo = (LinearLayout) findViewById(R.id.ly_remarkInfo);  //备注信息
        ly_AddressInfo = (LinearLayout) findViewById(R.id.ly_AddressInfo);//地址信息
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_payment.setOnClickListener(this);
        ly_AddressInfo.setOnClickListener(this);
        ly_remarkInfo.setOnClickListener(this);
    }

    private void setData() {
        orderAdapter = new OrderAdapter(this);
        lv_order.setAdapter(orderAdapter);
        orderAdapter.setData(carFoodList);
        tv_total_cost.setText("￥"+(money.add(distributionCost)));
        tv_total_costing.setText("￥"+(money.add(distributionCost)));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_payment:
                /*//跳转到支付页面，模拟支付
                Intent intent = new Intent();
                intent.setClass(OrderActivity.this,PaymentActivity.class);
                startActivity(intent);*/
                customer = user_name.getText().toString().trim();
                cust_phone = phone_number.getText().toString().trim();
                cust_address = address.getText().toString().trim();
                if (customer!=null&&cust_phone!=null&&cust_address!=null){
                    SharedPreferences sp = this.getSharedPreferences("data",MODE_PRIVATE);
                    user_id = sp.getString("id",null);
                    StringBuffer order_content = new StringBuffer();
                    for (Food foods : carFoodList) {
                        order_content.append(foods.getFod_name() + "X" + foods.getCount() + ";");
                    }
                    Log.i("aa",order_content.toString());

                    amount = tv_total_costing.getText().toString().trim();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    Date date = new Date(System.currentTimeMillis());
                    order_time = simpleDateFormat.format(date);
                    remarks = tv_remarkContent.getText().toString().trim();
                    Log.i("bb",customer+cust_phone+cust_address+remarks);
                    RequestBody body = new FormBody.Builder()
                            .add("order_name",customer)
                            .add("order_phone",cust_phone)
                            .add("order_cust",cust_address)
                            .add("order_content",order_content.toString())
                            .add("amount",amount)
                            .add("order_statu","0")
                            .add("order_time",order_time)
                            .add("user_id",user_id)
                            .add("remarks",remarks)
                            .build();
                    OkHttpClient okHttpClient = new OkHttpClient();
                    String url = Constant.WEB_SITE+Constant.REQUEST_ORDER_FOOD;
                    final Request request = new Request.Builder()
                            .url(url)
                            .post(body)
                            .build();
                    final Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string();
                            Log.i("cc",result);
                            Message msg = new Message();
                            msg.what = MSG_ORDER_OK;
                            msg.obj = result;
                            handler.sendMessage(msg);
                        }
                    });
                    finish();
                }else {
                    Toast.makeText(OrderActivity.this,"请添加收货信息",Toast.LENGTH_SHORT).show();
                }
                /*new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Response response = call.execute();
                            String result = response.body().string();
                            Message msg = new Message();
                            msg.what = MSG_ORDER_OK;
                            msg.obj = result;
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }).start();*/
                break;
            case R.id.ly_AddressInfo:
                Intent intent1 = new Intent();
                intent1.setClass(OrderActivity.this,AddressActivity.class);
                startActivityForResult(intent1,1);
                break;
            case R.id.ly_remarkInfo:
                Intent intent2 = new Intent();
                intent2.setClass(OrderActivity.this,RemarksActivity.class);
                startActivityForResult(intent2,3);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==2){
            user_name.setText(data.getStringExtra("customer"));
            phone_number.setText(data.getStringExtra("phone"));
            address.setText(data.getStringExtra("address"));
        }
        if (requestCode==3&&resultCode==4){
            tv_remarkContent.setText(data.getStringExtra("remarks"));
        }
    }

}
